package com.ruike.alisurface.services;

import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.mqtt.MQTTService;
import com.ruike.alisurface.mqtt.ServiceUtils;
import com.ruike.alisurface.utils.APPUtils;
import com.voodoo.lib_utils.L;

import org.eclipse.paho.android.service.MqttService;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Author: voodoo
 * CreateDate: 2020-03-27 027 下午 03:48
 * Description: 检测APP页面是否一直运行,不运行就直接启动
 */
public class AppRunMonitoringService extends Service {

    private Timer timer;
    private TimerTask task;
    public static boolean isNeedStop = false;

    @Override
    public void onCreate() {
        super.onCreate();
        startNotification();
        startTimer();
    }

    /**
     * 检测应用是否活着及mqtt 服务是否运行
     */
    private void checkIsAliveandServer() {
        if (isNeedStop) {
            return;
        }
        if (!APPUtils.isAppRunning(getApplicationContext(), BuildConfig.APPLICATION_ID)) {
            // APP没有运行，打开APP
            APPUtils.startOtherApp(getApplicationContext(), BuildConfig.APPLICATION_ID);
        } else if (!APPUtils.isAppRunningForeground(getApplicationContext(), BuildConfig.APPLICATION_ID)) {
            // 运行中，不在前台
            APPUtils.setTopApp(getApplicationContext(), BuildConfig.APPLICATION_ID);
        }
        if (!ServiceUtils.isServiceRunning(AppRunMonitoringService.this, MqttService.class.getName())) {
            L.e(" 检测到 MqttService 未启动 开始启动");
            ServiceUtils.startService(AppRunMonitoringService.this, MqttService.class);
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("Service退出");
        cancelTimer();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void startTimer() {
        cancelTimer();
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                checkIsAliveandServer();
            }
        };
        timer.schedule(task, 1000, 5_000); // 设置检测的时间周期(毫秒数)
    }

    private void cancelTimer() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (task != null) {
            task.cancel();
            task = null;
        }
    }

    /**
     * 创建一个 Notification 保证当前的服务不被清理
     */
    private void startNotification() {
        Notification notification = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.mipmap.icon_icon)
                .setTicker("保活服务通知")
                .setContentTitle("APK运行服务保活")
                .setContentText("创建通知保证服务运行")
                .build();
        startForeground(335, notification);
    }

}
